//
//  SHPTextView.swift
//  weibo
//
//  Created by songhuipan on 16/4/23.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit


class SHPTextView: UITextView {
    var offset:CGFloat = 100.00
    /// 占位文字
    var placeholder:String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    /// 重写font属性，实现外部修改文字大小
    override var font :UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        // 添加通知监听textview文字的变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 懒加载占位文字控件
    private lazy var placeholderLabel:UILabel = {
        let placeholderLabel:UILabel = UILabel(textColor: UIColor.grayColor(), textFont: 14)
        placeholderLabel.numberOfLines = 0
        return placeholderLabel
    }()
/// 销毁通知观察者
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension SHPTextView {
/// 监听文字改变，隐藏占位问题,接收通知后执行的方法
    @objc private func textDidChange (){
        placeholderLabel.hidden = self.hasText()
//        print(self.hasText())
        // 设置文字宽高约束
        let constraintSize = CGSizeMake(kScreenWidth, kScreenHeigth)
        // 根据约束的文字的宽高，该方法是UIView的方法
        let size = self.sizeThatFits(constraintSize)
        
        if size.height >= offset  {
            for v in subviews{
                if v .isKindOfClass(SHPAlbumCollectionView){
                    offset += 20
                    v.snp_updateConstraints(closure: { (make) -> Void in
                        make.top.equalTo(self).offset(offset)
                    })
                    layoutIfNeeded()
                }
            }
            
        }
        
    }
    // MARK:设置界面UI
    private func setupUI (){
        backgroundColor = UIColor.whiteColor()
        addSubview(placeholderLabel)
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(8)
            make.leading.equalTo(5)
            make.width.equalTo(kScreenWidth-10)
        }
    }
    
}







































